<template>
  <div class="app-container" v-loading="loading">
    <div class="search-container">
      <FormList :initForm="initSearchForm" v-model:formModel="searchForm"></FormList>
    </div>
    <el-card shadow="never" class="table-container">
      <!-- <template #header>
        <el-button
          type="primary"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />添加</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />一键停工</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />代付费率设置</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-delete />批量删除</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />解除所有冻结</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />一键修改最低接单金额</el-button
        >
        <el-button
          type="success"
          @click="handleTableBtnClick({}, 'add')"
          ><i-ep-plus />一键解绑TG</el-button
        >
      </template> -->
      <div
        class="info-container border-[#e6e6e6] border-solid border p-[10px] border-l-[5px] mb-[10px]"
      >
        交易订单：<span>{{ tableDatasObj.paging.total }}</span
        >单 成功订单：<span>{{ tableDatasObj.success_count }}</span
        >单 当前订单总金额：<span>{{ tableDatasObj.total_amount }}</span
        >元 成交总金额：<span>{{ tableDatasObj.success_amount }}</span
        >元 成功率<span>{{ successRateCom }}</span
        >%
      </div>
      <comTable
        :data="tableDatasCom"
        :config="tableconfig"
        :tableHeader="tableHeader"
        @link-click="handleTableBtnClick"
      >
        <template #status="{ row, index }">
          <el-switch
            v-model="row.statusCom"
            inline-prompt
            active-text="开"
            inactive-text="关"
            @change="(val) => handleChangeStatus(val, row, index)"
          />
        </template>
        <template #qr_code="{ row, index }">
          <template v-if="row.qr_code">
            <el-button
              type="primary"
              size="small"
              h-22px
              line-height-22px
              pl-5px
              pr-5px
              @click="handleTableBtnClick(row, 'qr_code')"
            >
              查看二维码
            </el-button>
          </template>
          <template v-else>-</template>
        </template>
      </comTable>

      <pagination
        v-if="tableDatasObj.paging.total > 0"
        v-model:total="tableDatasObj.paging.total"
        v-model:page="tableDatasObj.paging.page"
        v-model:limit="tableDatasObj.paging.limit"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <template v-if="dialog.type === 'detail'">
        <el-descriptions title="" :column="2">
          <el-descriptions-item
            v-for="(item, index) in config.table"
            :key="index"
            :label="item.label"
            >{{ dialog.singleData[item.key] }}</el-descriptions-item
          >
        </el-descriptions>
        <!-- {{ config.table }} -->
        <!-- {{ dialog.singleData }} -->
      </template>
      <template v-else>
        <FormList
          v-if="initDialogForm.initKeys.length"
          v-model:formRef="formDialogId"
          v-model:formModel="formDialogModel"
          :initForm="initDialogForm"
        ></FormList>
      </template>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialog.leftBtnText" type="primary" @click="handleLeftClick">{{
            dialog.leftBtnText
          }}</el-button>
          <el-button v-if="dialog.rightBtnText" @click="handleRightClick">{{
            dialog.rightBtnText
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { watch, inject } from "vue";
import { useRoute } from "vue-router";
import { FormInstance } from "element-plus";
import FormList from "@/components/FormList/index.vue";
import comTable from "@/components/comTable/comTable.vue";
import { order_list as list, edit, deleteById, success } from "@/api/other/access";
import { all as ms_all } from "@/api/other/ms";
// import { payment_stat as list } from "@/api/other/payment";
// import { ProductListVO } from "@/api/other/types";
// import { usePayProductStore } from "@/store";

import channelConfig from "@/plugins/channels.config.ts";

const getFormatDate = inject("getFormatDate");
// const getTimestamp: number | null = inject("getTimestamp");

const route = useRoute();

const config = channelConfig(route.meta.page, route.meta.pass_code);

console.log("route", route);

const tableDatasObj = ref({
  list: [],
  paging: {
    limit: 20,
    page: 1,
    total: 0,
  },
  queryParams: {},
});
const loading = ref(false);

// 时间类型(1:创建时间；2:修改时间)
// "status": "订单状态(1:待处理；2:处理中；3:已完成；4:处理失败)",
// "return_status": "通知状态 (1:未支付；2:回调成功；3:回调失败)",
// "correct_status": "冲正状态(1:正常；2:已冲正)",
const options = {
  status: [
    {
      label: "等待支付",
      value: "1",
    },
    {
      label: "已支付",
      value: "2",
    },
    {
      label: "已关闭",
      value: "3",
    },
    {
      label: "已过期",
      value: "4",
    },
  ],
  return_status: [
    {
      label: "未支付",
      value: "1",
    },
    {
      label: "回调成功",
      value: "2",
    },
    {
      label: "回调失败",
      value: "3",
    },
  ],
  is_delete: [
    {
      label: "已删除",
      value: "1",
    },
    {
      label: "未删除",
      value: "0",
    },
  ],
  device_type: [
    {
      label: "未知",
      value: "0",
    },
    {
      label: "安卓",
      value: "1",
    },
    {
      label: "苹果",
      value: "2",
    },
    {
      label: "PC",
      value: "3",
    },
  ],
};

// const return_statusOption = [
//   {
//     label: "未支付",
//     value: "1",
//   },
//   {
//     label: "回调成功",
//     value: "2",
//   },
//   {
//     label: "回调失败",
//     value: "3",
//   },
// ];
// const correct_statusOption = [
//   {
//     label: "正常",
//     value: "1",
//   },
//   {
//     label: "已冲正",
//     value: "2",
//   },
// ];
// const workStatusOptions = [
//   {
//     label: "关闭",
//     value: "2",
//   },
//   {
//     label: "开启",
//     value: "1",
//   },
// ];

const searchForm = ref({});
const initSearchForm = ref({
  // 表单标签位置
  // labelPosition: "right",
  formAttrs: {
    // 是否内联
    inline: true,
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 6,
  },
  // 初始化表单字段
  initKeys: [
    ...config.search
      .filter((item) => !item.noDisplay)
      .map((item) => {
        return {
          type: item.type ? item.type : "input",
          // 唯一标识
          key: item.key,
          // 表单属性
          formAttrs: {
            label: item.label,
            labelWidth: item.label.length > 4 ? "120px" : null,
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请" + (item.type ? "选择" : "输入") + item.label,
            // 是否可清空
            clearable: true,
            filterable: true,
            options: [],
          },
          // 控制事件
          controlOn: {},
        };
      }),
    {
      // 类型
      type: "buttons",
      // 按钮
      btns: [
        {
          // 文本
          text: "搜索",
          // 控制属性
          controlAttrs: {
            // 类型
            type: "primary",
            icon: "search",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: (e: Event, formRef: FormInstance, data: object) => {
              formRef.validate((valid) => {
                if (valid) {
                  tableDatasObj.value.paging.page = 1;

                  let tempData = { ...data };

                  // tempData.start_time = getTimestamp(data.start_time);
                  // tempData.end_time = getTimestamp(data.end_time);

                  tableDatasObj.value.queryParams = tempData;

                  handleQuery(tableDatasObj.value.paging);
                }
              });
            },
          },
        },
        {
          // 文本
          text: "重置",
          // 控制属性
          controlAttrs: {
            icon: "refresh",
          },
          // 控制事件
          controlOn: {
            // 点击
            click: resetQuery,
          },
        },
      ],
    },
  ],
});

// merchant_all().then((res) => {
//   initSearchForm.value.initKeys[0].controlAttrs.options = res.map((item) => ({
//     label: item.mer_name,
//     value: item.id,
//   }));
// });

let proLists = [];

import { usePayProductStore } from "@/store";
(async () => {
  proLists = await usePayProductStore().loadPayProducts();

  initSearchForm.value.initKeys[0].controlAttrs.options = proLists.map((item) => ({
    label: item.pro_name,
    value: item.id,
  }));
})();

ms_all().then((res) => {
  initSearchForm.value.initKeys[1].controlAttrs.options = res.map((item) => ({
    label: item.ms_name,
    value: item.id,
  }));
  initSearchForm.value.initKeys[2].controlAttrs.options = res.map((item) => ({
    label: item.ms_name,
    value: item.id,
  }));
});

const controls = initSearchForm.value.initKeys;

config.search.map((item, i) => {
  const key = item.key;
  if (options[key]) {
    controls[i].options = options[key];
  }
});

// (async () => {
//   initSearchForm.value.initKeys[1].controlAttrs.options = (
//     await usePayProductStore().loadPayProducts()
//   ).map((item) => ({
//     label: item.pro_name,
//     value: item.id,
//   }));
// })();

/** 重置查询 */
function resetQuery(e: Event, formRef: FormInstance, data: object) {
  // 重置表单
  formRef.resetFields();
  // 查询
  tableDatasObj.value.paging.page = 1;
  tableDatasObj.value.paging.limit = 20;
  tableDatasObj.value.queryParams = { ...searchForm.value };
  const params = {
    ...tableDatasObj.value.queryParams,
    ...data,
    ...tableDatasObj.value.paging,
  };

  handleQuery(params);
}

// 表*********************************************
const tableDatasCom = computed(() => {
  return tableDatasObj.value.list.map((item: any) => {
    return {
      ...item,
      createtimeCom: getFormatDate(item.createtime),
      updatetimeCom: getFormatDate(item.updatetime),
      time_stampCom: getFormatDate(item.time_stamp),
      incomeAmountCom: item.service_fee - item.dl_profit - item.ms_profit,
      is_deleteCom: options.is_delete.find(
        (tItem) => tItem.value === item.is_delete.toString()
      )?.label,
      statusCom: options.status.find((tItem) => tItem.value === item.status.toString())
        ?.label,
      return_statusCom: options.return_status.find(
        (tItem) => tItem.value === item.return_status.toString()
      )?.label,
      device_typeCom: options.device_type.find(
        (tItem) => tItem.value === item.device_type.toString()
      )?.label,
    };
  });
});
const tableconfig = {
  // tableHeight: 480, //表格高度
  isSelection: false, //显示复选框
  isRowClick: false, //使用行点击
  isStripe: true, //隐藏斑马纹，与背景色不可同时用
  isShowSummary: false, //显示共计
  isIndex: true, //自定义序号
  isNeedPagination: true, //是否需要分页
};
const tableHeader = [
  ...config.table
    .filter((item) => !item.noDisplay)
    .map((item) => {
      return {
        label: item.label,
        prop: item.key,
        type: item.type,
        width: 200,
      };
    }),
  {
    label: "操作",
    isSort: false,
    prop: "operation",
    columnAttrs: {
      fixed: "right",
      width: "220",
    },
    children: [
      {
        type: "button",
        btnText: "拉黑IP",
        title: "del",
        controlAttrsFunc: (obj) => {
          let result = {};

          // if (obj.is_delete.toString() === "1") {
          //   result.style.display= 'none';
          // }

          return result;
        },
      },
      {
        type: "button",
        btnText: "确认收款",
        title: "confirm",
        controlAttrsFunc: (obj) => {
          let result = {};

          if (obj.status.toString() === "1") {
            result.disabled = false;
          } else {
            if (!result.style) {
              result.style = {};
            }
            result.style.display = "none";
          }

          return result;
        },
      },
      {
        type: "button",
        btnText: "详情",
        title: "detail",
      },
    ],
  },
];

/**
 * 查询
 */
function handleQuery(paging: { page: number; limit: number }) {
  loading.value = true;
  list({
    ...tableDatasObj.value.paging,
    ...tableDatasObj.value.queryParams,
    // pro_id: route.meta.id,
  })
    .then((res) => {
      tableDatasObj.value.paging.total = res.total;
      tableDatasObj.value.list = res.list;
      tableDatasObj.value.success_amount = res.success_amount;
      tableDatasObj.value.success_count = res.success_count;
      tableDatasObj.value.total_amount = res.total_amount;
    })
    .finally(() => {
      loading.value = false;
    });
  // if (tableDatasObj.paging.typeCode) {
  // loading.value = true;
  // getDictPage(queryParams)
  //   .then(({ data }) => {
  //     dictList.value = data.list;
  //     total.value = data.total;
  //   })
  //   .finally(() => (loading.value = false));
  // }
}

// const statInfo = ref({});
// const dealSuccessRateCom = ref(0);
// const orderSuccessRateCom = ref(0);
const successRateCom = computed(() => {
  return tableDatasObj.value.paging.total
    ? (
        (tableDatasObj.value.success_count * 100) /
        tableDatasObj.value.paging.total
      ).toFixed(2)
    : 0;
});
// const dealSuccessRateCom = computed(() => {
//   return statInfo.value.total_amount
//     ? ((statInfo.value.success_amount * 100) / statInfo.value.total_amount).toFixed(2)
//     : 0;
// });
// // const orderSuccessRateCom.value = computed(() => {
// //   return statInfo.value.period_count
// //     ? statInfo.value.period_success_count * 100 / statInfo.value.period_count
// //     : 0;
// // });

// // 统计
// function loadstat() {
//   loading.value = true;
//   stat()
//     .then((res) => {
//       statInfo.value = res;
//     })
//     .finally(() => (loading.value = false));
// }

// loadstat();
// 完*********************************************

const initDialogForm = ref({
  // 表单标签位置
  formAttrs: {
    // 是否内联
    // inline: true,
    labelPosition: "top",
  },
  rowAttrs: {
    // 行内表单数量
    columnsNum: 1,
  },
  // 初始化表单字段
  initKeys: <any>[],
});

const isHasOptions = [
  {
    // 标签
    label: "关闭",
    // 值
    value: 0,
  },
  {
    // 标签
    label: "开启",
    // 值
    value: 1,
  },
];

// 处理表格按钮点击事件
function handleTableBtnClick(row: object, title: string) {
  // 显示对话框
  dialog.type = title;
  dialog.visible = true;
  dialog.singleData = tableDatasCom.value.find((item) => item.id === row.id);

  // 新增支付产品
  if (title === "add") {
    dialog.title = "新增支付产品";
    dialog.leftBtnText = "确 定";
    dialog.rightBtnText = "取 消";

    initDialogForm.value.initKeys.push(
      ...[
        // 产品名称
        // 通道代码
        // 通道显示
        // 状态
        {
          // 类型
          type: "input",
          // 唯一标识
          key: "qqq5",
          // 表单属性
          formAttrs: {
            label: "产品名称",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请输入产品名称",
            // 是否可清空
            clearable: true,
          },
          // 控制事件
          controlOn: {},
        },
        {
          // 类型
          type: "input",
          // 唯一标识
          key: "qqq5",
          // 表单属性
          formAttrs: {
            label: "通道代码",
          },
          // 控制属性
          controlAttrs: {
            // 提示文本
            placeholder: "请输入通道代码",
            // 是否可清空
            clearable: true,
          },
          // 控制事件
          controlOn: {},
        },
        {
          // 类型
          type: "switch",
          // 唯一标识
          key: "qqq5",
          // 表单属性
          formAttrs: {
            label: "通道显示",
          },
          // 控制属性
          controlAttrs: {
            value: false,
          },
          // 控制事件
          controlOn: {},
        },
        {
          // 类型
          type: "switch",
          // 唯一标识
          key: "qqq5",
          // 表单属性
          formAttrs: {
            label: "状态",
          },
          // 控制属性
          controlAttrs: {
            value: false,
          },
          // 控制事件
          controlOn: {},
        },
      ]
    );
    // 查看二维码
  } else if (title === "qr_code") {
    dialog.visible = false;

    ElMessageBox({
      title: "查看二维码",
      center: true,
      showConfirmButton: false,
      message: h(ElImage, {
        src: import.meta.env.VITE_APP_BASE_API + row.qr_code,
        fit: "contain",
        style: {
          width: "220px",
        },
      }),
    });
    // 删除
  } else if (title === "del") {
    dialog.visible = false;

    ElMessageBox.confirm("你确定要删除这条信息吗?", "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      title: "提示",
    }).then(() => {
      let params = {
        ids: [row].map((item) => item.id).join(","),
      };

      deleteById(params).then((res) => {
        if (tableDatasObj.value.list.length === 1) {
          if (tableDatasObj.value.paging.page > 1) {
            --tableDatasObj.value.paging.page;
          }
        }
        handleQuery();
      });
    });
  } else if (title === "confirm") {
    dialog.visible = false;

    ElMessageBox.prompt("你确定要确认收款吗", "敏感操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /[\d,\w]{1,10}/,
      inputPlaceholder: "请输入Google验证码",
      inputErrorMessage: "请输入正确的Google验证码",
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          const value = instance.inputValue;
          let params = { order_id: row.id, google_code: value.trim() };
          success(params).then(() => {
            ElMessage.success("确认收款成功");
            done();
            handleQuery();
          });
        } else {
          done();
        }

        return;
      },
    });

    // ElMessageBox.confirm("你确定要确认收款吗?", "Warning", {
    //   confirmButtonText: "确定",
    //   cancelButtonText: "取消",
    //   title: "提示",
    // }).then(() => {
    //   let params = { order_id: row.id };
    //   success(params).then(() => {
    //     ElMessage.success("确认收款成功");
    //   });
    // });
  } else if (title === "detail") {
    dialog.visible = true;
  }
}

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
  leftBtnText: "确 定",
  rightBtnText: "取 消",
});

let formDialogId = ref<FormInstance>();

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  // formDialogId.value?.resetFields();
  // formDialogId.value?.clearValidate();
  formDialogId.value = {};
  formDialogModel.value = {};
  initDialogForm.value.initKeys.splice(0);
  dialog.visible = false;
}

let formDialogModel = ref({});
function handleLeftClick() {
  // formDialogId.

  closeDialog();
}
function handleRightClick() {
  // formDialogId.
  closeDialog();
}

function handleChangeStatus(val, row, index) {}

onMounted(() => {
  tableDatasObj.value.queryParams = { ...searchForm.value };

  handleQuery(tableDatasObj.value.paging);
});
</script>

<style lang="scss" scoped>
.info-container {
  font-size: var(--el-font-size-extra-small);

  span {
    background-color: #1e9fff;
    display: inline-block;
    padding: 0 10px;
    margin: 0 5px;
    color: #fff;
  }
}
</style>
